package stack;

import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

/**
 * @author : Rookie
 * @description : 用两个队列实现栈
 * @date : 2023/10/10
 */
public class ImplStackByQueue {

    private final Queue<Integer> queue1;

    private final Queue<Integer> queue2;

    public ImplStackByQueue() {
        this.queue1 = new LinkedList<>();
        this.queue2 = new LinkedList<>();
    }

    public void push(int e) {
        this.queue1.offer(e);
    }

    public int pop() {
        while (queue1.size()>1) {
            queue2.offer(queue1.poll());
        }
        Integer target = queue1.poll();
        while (!queue2.isEmpty()) {
            queue1.offer(queue2.poll());
        }
        if (Objects.isNull(target)) {
            throw new RuntimeException("queue is empty!");
        }
        return target;
    }

    public int peek() {
        while (queue1.size()>1) {
            queue2.offer(queue1.poll());
        }
        Integer target = queue1.peek();
        while (!queue2.isEmpty()) {
            queue1.offer(queue2.poll());
        }
        if (Objects.isNull(target)) {
            throw new RuntimeException("queue is empty!");
        }
        return target;
    }

    public boolean isEmpty() {
        return queue1.isEmpty();
    }

    public static void main(String[] args) {
        ImplStackByQueue stack = new ImplStackByQueue();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        while (!stack.isEmpty()) {
            System.out.println("元素" + stack.pop() + "出栈");
        }
        stack.push(4);
        System.out.println("栈内元素：" + stack.queue1);
    }
}
